<?php
/**  
 * @file token.php  
 * @author 辰然 <3469807212@qq.com>  
 * @created 2024年11月30日  
 * @signature "创意无限"  
 * @copyright Copyright (c) 2024 辰然. All rights reserved. 本软件版权归辰然所有，未经许可，不得开源或用于商业用途。  
 *  
 * 描述: token校验
 * 注意: 根据版权声明，此代码允许开源。  
 */  
header('Content-Type: application/json; charset=utf-8');

// 允许跨域请求
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

require_once __DIR__ . '/TokenManager.php';
$tokenManager = new TokenManager();

// 获取请求数据
$requestData = json_decode(file_get_contents('php://input'), true);
if (!$requestData) {
    response(1, '无效的请求数据');
}

// 响应函数
function response($code, $message, $data = null) {
    echo json_encode([
        'code' => $code,
        'message' => $message,
        'data' => $data
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

// 根据请求动作处理
switch ($requestData['action']) {
    case 'validate':
        if (empty($requestData['token'])) {
            response(1, '缺少 Token');
        }

        $result = $tokenManager->validateToken($requestData['token']);
        if ($result['valid']) {
            response(0, 'Token 验证成功', $result);
        } else {
            $errorMessage = $result['message'] ?? 'Token 验证失败';
            error_log("Token validation failed: {$errorMessage} for token: {$requestData['token']}");
            response(1, $errorMessage);
        }
        break;

    case 'refresh':
        if (empty($requestData['token'])) {
            response(1, '缺少 Token');
        }

        $result = $tokenManager->refreshToken($requestData['token']);
        if ($result['success']) {
            response(0, 'Token 刷新成功', $result);
        } else {
            $errorMessage = $result['message'] ?? 'Token 刷新失败';
            error_log("Token refresh failed: {$errorMessage} for token: {$requestData['token']}");
            response(1, $errorMessage);
        }
        break;

    default:
        response(1, '未知的操作类型');
}
?>